// take the ws reply data for use
import { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'
import { isString, isObjectHasKey } from 'jsonql-params-validator'
import { JsonqlError, clientErrorsHandler } from 'jsonql-errors'

import getDebug from '../utils/get-debug'
const debugFn = getDebug('extract-ws-payload')

const keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]

/**
 * @param {object} payload should be string when reply but could be transformed
 * @return {boolean} true is OK
 */
const isWsReply = payload => {
  const { data } = payload;
  if (data) {
    let result = keys.filter(key => isObjectHasKey(data, key))
    return (result.length === keys.length) ? data : false;
  }
  return false;
}

/**
 * @param {object} payload This is the entire ws Event Object
 * @return {object} false on failed
 */
const extractWsPayload = payload => {
  const { data } = payload;
  let json = isString(data) ? JSON.parse(data) : data;
  // debugFn('extractWsPayload', json)
  let fdata;
  if ((fdata = isWsReply(json)) !== false) {
    return {
      resolverName: fdata[WS_EVT_NAME],
      data: fdata[WS_DATA_NAME],
      type: fdata[WS_REPLY_TYPE]
    };
  }
  throw new JsonqlError('payload can not be decoded', payload)
}
// export it
export default extractWsPayload
